package cc.wanforme.chipmunity.system.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.system.event.BaseEvent;
import cc.wanforme.chipmunity.system.event.PassageEvent;
import cc.wanforme.chipmunity.system.mapper.PassageMapper;
import cc.wanforme.chipmunity.system.mapper.user.UserMapper;
import cc.wanforme.chipmunity.system.po.Passage;
import cc.wanforme.chipmunity.system.po.user.User;
import cc.wanforme.chipmunity.system.service.interfaces.PassageService;

/**
 * @author wanne
 * 2019年8月17日
 * 
 */
@Service
public class PassageServiceImpl implements PassageService, ApplicationEventPublisherAware{
	
	private ApplicationEventPublisher publisher;
	
	@Autowired
	private PassageMapper passageMapper;
	
	@Autowired
	private UserMapper userMapper;

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}
	
	@Override
	public WebResponse savePassage(Passage passage) {
		if(passage.getSubjectId() == null ) {
			return WebResponse.fail("未知主题");
		}
		if(StringUtils.isAnyBlank(passage.getTitle(), passage.getRtfContent(), passage.getRtfContent())) {
			return WebResponse.fail("信息不完整");
		}
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication == null) {
			return WebResponse.fail("未登录");
		}
		
		User user = userMapper.selectUserByUsername(authentication.getName());
		Passage passage_persistent = new Passage(passage.getSubjectId(), passage.getTitle(), 
				user.getId(), user.getName(), passage.getRtfContent());
		passageMapper.insertPassage(passage_persistent);
		return WebResponse.success("文章发送成功");
	}
	
	
	@Override
	public WebResponse updatePassage(Passage passage) {
		if(passage.getId() == null) {
			return WebResponse.fail("未知文章");
		}
		
		if(passage.getState() != null) {
			Passage source = passageMapper.selectPassage(passage.getId());
			publisher.publishEvent(new PassageEvent(source, BaseEvent.OperateType.UPDATE_DELETE));
		}
		
		passageMapper.updatePassage(passage);
		return WebResponse.success("更新成功");
	}
	
	@Override
	public WebResponse deletePassage(Long id) {
		Passage source = passageMapper.selectPassage(id);
		publisher.publishEvent(new PassageEvent(source, BaseEvent.OperateType.DELETE));
		
		passageMapper.deletePassage(id);
		return WebResponse.fail("删除成功");
	}
	
}
